import {Buffer} from "buffer";
import {TI} from "./TI";
import {Date_time_s} from "./Date_time_s";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";


export class TimeTag implements AxdrType {

    dataCode: Buffer | null = null;
    ti: TI | null = null;
    dts: Date_time_s | null = null;

    constructor() {
    }

    set_dataCode(dataCode: Buffer) {
        this.dataCode = dataCode;
    }

    set_dts_ti(dts: Date_time_s, ti: TI) {
        this.dts = dts;
        this.ti = ti;
    }

    setDTS(dts: Date_time_s){
        this.dts = dts;
    }

    setTI(ti: TI){
        this.ti = ti;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.dts = new Date_time_s();
        codeLength += this.dts.decode(input);

        this.ti = new TI();
        codeLength += this.ti.decode(input);


        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.ti != null && this.dts != null) {
                codeLength = 0;
                codeLength += this.ti.encode(output);
                codeLength += this.dts.encode(output);
            } else {
                throw new Error("ti or dts is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.ti != null && this.dts != null) {
            return "sequence: {" + "dts: " + this.dts + ", ti: " + this.ti + "}";
        } else {
            return "ti or dts is null";
        }
    }

}
